package org.jeecg.modules.demo.ddyht.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ddyht.entity.DdygPici;
import org.jeecg.modules.demo.ddyht.entity.DdygSale;
import org.jeecg.modules.demo.ddyht.entity.DdygStock;
import org.jeecg.modules.demo.ddyht.service.IDdygPiciService;
import org.jeecg.modules.demo.ddyht.service.IDdygStockService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 进货单
 * @Author: jeecg-boot
 * @Date:   2025-02-23
 * @Version: V1.0
 */
@Api(tags="进货单")
@RestController
@RequestMapping("/ddyht/jxcStock")
@Slf4j
public class DdygStockController extends JeecgController<DdygStock, IDdygStockService> {
	@Autowired
	private IDdygStockService jxcStockService;
	@Autowired
	private IDdygPiciService ddygPiciService;

	/**
	 * 分页列表查询
	 *
	 * @param ddygStock
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "进货单-分页列表查询")
	@ApiOperation(value="进货单-分页列表查询", notes="进货单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DdygStock>> queryPageList(DdygStock ddygStock,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		QueryWrapper<DdygStock> queryWrapper = QueryGenerator.initQueryWrapper(ddygStock, req.getParameterMap());
		Page<DdygStock> page = new Page<DdygStock>(pageNo, pageSize);
		IPage<DdygStock> pageList = jxcStockService.page(page, queryWrapper);
		List<DdygStock> company = jxcStockService.getBycompany(ddygStock.getUsername());
		if (StringUtils.isNotBlank(ddygStock.getType1())){
			List<DdygStock> list = new ArrayList<>();
			String type1 = ddygStock.getType1();
			if (type1.equals("only")){
				if (ddygStock.getType2().equals("time")){
					if (StringUtils.isBlank(ddygStock.getBeginTime()) || ddygStock.getBeginTime() == null || ddygStock.getBeginTime() == ""){
						int size = company.size();
						int page2 = (size + 9) / 10;
						pageList.setTotal(size);
						pageList.setPages(page2);
						pageList.setRecords(company);
						return Result.OK(pageList);
					}
					for (int i = 0; i < company.size(); i++) {
						// company.get(i).getCreateTime()日期格式2025/04/27
						String beginTime = ddygStock.getBeginTime();
						String endTime = ddygStock.getEndTime();
						DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
						LocalDate startDate = LocalDate.parse(beginTime, formatter);
						LocalDate endDate = LocalDate.parse(endTime, formatter);
						log.info("company.get(i).getCreateTime().substring(0,10)："+company.get(i).getCreateTime().substring(0,10));
						LocalDate createDate = LocalDate.parse(company.get(i).getCreateTime().substring(0,10), formatter);
						if (!createDate.isBefore(startDate) && !createDate.isAfter(endDate)) {
							list.add(company.get(i));
						}
					}
				}
				if (ddygStock.getType2().equals("model")){
					if (StringUtils.isBlank(ddygStock.getType3())){
						int size = company.size();
						int page2 = (size + 9) / 10;
						pageList.setTotal(size);
						pageList.setPages(page2);
						pageList.setRecords(company);
						return Result.OK(pageList);
					}
					String type3 = ddygStock.getType3();
					for (int i = 0; i < company.size(); i++) {
						if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type3)){
							list.add(company.get(i));
						}
					}
				}
				if (ddygStock.getType2().equals("traner")){
					if (StringUtils.isBlank(ddygStock.getType3())){
						int size = company.size();
						int page2 = (size + 9) / 10;
						pageList.setTotal(size);
						pageList.setPages(page2);
						pageList.setRecords(company);
						return Result.OK(pageList);
					}
					String type3 = ddygStock.getType3();
					for (int i = 0; i < company.size(); i++) {
						if (StringUtils.containsIgnoreCase(company.get(i).getSeller(),type3)){
							list.add(company.get(i));
						}
					}
				}
			}else if (type1.equals("all")){
				if (StringUtils.isNotBlank(ddygStock.getBeginTime()) && ddygStock.getBeginTime() != null && ddygStock.getBeginTime() != ""){
					for (int i = 0; i < company.size(); i++) {
						// company.get(i).getCreateTime()日期格式2025/04/27
						String beginTime = ddygStock.getBeginTime();
						String endTime = ddygStock.getEndTime();
						DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
						LocalDate startDate = LocalDate.parse(beginTime, formatter);
						LocalDate endDate = LocalDate.parse(endTime, formatter);
						LocalDate createDate = LocalDate.parse(company.get(i).getCreateTime().substring(0,10), formatter);
						if (!createDate.isBefore(startDate) && !createDate.isAfter(endDate)) {
//						if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type2)&& StringUtils.containsIgnoreCase(company.get(i).getBuyer(),type3)){
							if (StringUtils.isNotBlank(ddygStock.getType2()) && StringUtils.isNotBlank(ddygStock.getType3())){
								String type2 = ddygStock.getType2();
								String type3 = ddygStock.getType3();
								if (type3.equals(company.get(i).getSeller())){
									if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type2)){
										list.add(company.get(i));
									}
								}
							}else if (StringUtils.isNotBlank(ddygStock.getType2()) && StringUtils.isBlank(ddygStock.getType3())){
								String type2 = ddygStock.getType2();
								if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type2)){
									list.add(company.get(i));
								}
							}else if (StringUtils.isBlank(ddygStock.getType2()) && StringUtils.isNotBlank(ddygStock.getType3())){
								String type3 = ddygStock.getType3();
								if (type3.equals(company.get(i).getSeller())){
										list.add(company.get(i));
								}
							}else if (StringUtils.isBlank(ddygStock.getType2()) && StringUtils.isBlank(ddygStock.getType3())){
								return Result.error("参数为空");
							}
						}
					}
				}else if (StringUtils.isNotBlank(ddygStock.getType2()) && StringUtils.isNotBlank(ddygStock.getType3())){
					for (int i = 0; i < company.size(); i++) {
						String type2 = ddygStock.getType2();
						String type3 = ddygStock.getType3();
						if (type3.equals(company.get(i).getSeller())){
							if (StringUtils.containsIgnoreCase(company.get(i).getModel(),type2)){
								list.add(company.get(i));
							}
						}
					}
				}else {
					return Result.error("参数不足");
				}
			}
			int size = list.size();
			int page2 = (size + 9) / 10;
			pageList.setTotal(size);
			pageList.setPages(page2);
			pageList.setRecords(list);
			return Result.OK(pageList);
		}
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param ddygStock
	 * @return
	 */
	@AutoLog(value = "进货单-添加")
	@ApiOperation(value="进货单-添加", notes="进货单-添加")
	@RequiresPermissions("ddyht:jxc_stock:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DdygStock ddygStock) {
		jxcStockService.save(ddygStock);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param ddygStock
	 * @return
	 */
	@AutoLog(value = "进货单-编辑")
	@ApiOperation(value="进货单-编辑", notes="进货单-编辑")
	@RequiresPermissions("ddyht:jxc_stock:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DdygStock ddygStock) {
		jxcStockService.updateById(ddygStock);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进货单-通过id删除")
	@ApiOperation(value="进货单-通过id删除", notes="进货单-通过id删除")
	@RequiresPermissions("ddyht:jxc_stock:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		jxcStockService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "进货单-批量删除")
	@ApiOperation(value="进货单-批量删除", notes="进货单-批量删除")
	@RequiresPermissions("ddyht:jxc_stock:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.jxcStockService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "进货单-通过id查询")
	@ApiOperation(value="进货单-通过id查询", notes="进货单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DdygStock> queryById(@RequestParam(name="id",required=true) String id) {
		DdygStock ddygStock = jxcStockService.getById(id);
		if(ddygStock ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ddygStock);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ddygStock
    */
//    @RequiresPermissions("ddyht:jxc_stock:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DdygPici ddygStock) {
        return exportXls(request, ddygStock, DdygPici.class, "进货批次信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
//    @RequiresPermissions("ddyht:jxc_stock:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importExcel2(request, response, DdygPici.class);
    }
	 public Result<?> importExcel2(HttpServletRequest request, HttpServletResponse response, Class<DdygPici> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 log.info("文件导入:{}" + file.getInputStream());
				 List<DdygPici> list0 = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
				 log.info("文件导入:{}" + list0);
				 List<DdygPici> list = new ArrayList<>();
				 for (int i = 0; i < list0.size(); i++) {
					 DdygPici ddygPici = list0.get(i);
					 String companyId = ddygPici.getCompanyId();
                     if (companyId != null) {
                         companyId = companyId.trim();
                         ddygPici.setCompanyId(companyId);
                     }
					 if (StringUtils.isNotBlank(ddygPici.getModel())&& StringUtils.isNotBlank(ddygPici.getNumber())&& StringUtils.isNotBlank(ddygPici.getUnitPrice())&& StringUtils.isNotBlank(ddygPici.getCompanyId())&& StringUtils.isNotBlank(ddygPici.getOrstate())&& StringUtils.isNotBlank(ddygPici.getTraner())){
						 list.add(ddygPici);
					 }
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
				 ddygPiciService.add(list);
//				 ddygPiciService.saveBatch(list);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				 String msg = e.getMessage();
				 log.error(msg, e);
				 if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					 return Result.error("文件导入失败:有重复数据！");
				 }else{
					 return Result.error("文件导入失败:" + e.getMessage());
				 }
				 //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }
	 public ModelAndView exportXls(HttpServletRequest request, DdygPici object, Class<DdygPici> clazz, String title) {
		 // Step.1 组装查询条件
		 QueryWrapper<DdygPici> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 queryWrapper.in("id",selectionList);
		 }

		 List<DdygPici> exportList = new ArrayList<DdygPici>();
		 // Step.2 获取导出数据
		 if (oConvertUtils.isNotEmpty(selections)){
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 List<DdygPici> ddygPicis = new ArrayList<DdygPici>();
			 for (int i = 0; i < selectionList.size(); i++) {
				 String id = selectionList.get(i);
				 ddygPicis = ddygPiciService.getByallId(object.getUsername(), id);
				 for (int i1 = 0; i1 < ddygPicis.size(); i1++) {
					 ddygPicis.get(i1).setTime(id.substring(0, 8));
					 exportList.add(ddygPicis.get(i1));
				 }
			 }
		 }else {
			 List<DdygPici> bycompanySale = ddygPiciService.getBycompanySale(object.getUsername(), "1");
			 for (int i = 0; i < bycompanySale.size(); i++) {
				 bycompanySale.get(i).setTime(bycompanySale.get(i).getId().substring(0, 8));
			 }
			 exportList = bycompanySale;
		 }
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		 exportList.sort((o1, o2) -> {
			 LocalDate date1 = LocalDate.parse(o1.getTime(), formatter);
			 LocalDate date2 = LocalDate.parse(o2.getTime(), formatter);
			 return date2.compareTo(date1); // 最新在前
		 });
		 // Step.2 获取导出数据
//		 List<DdygStock> exportList = jxcStockService.getBycompany(object.getUsername());
//		 List<DdygPici> exportList = ddygPiciService.getBycompanySale(object.getUsername(), "1");
//		 List<DdygSale> exportList = service.list(queryWrapper);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, title);
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		 exportParams.setImageBasePath("C:/upload/sc");
//		 exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload());
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }
}
